<?php

/**
 * 内容关联的门店列表
 * Class RelatedListAction
 */

use Doraemon\tools\ActionLog;
use Hhz\AdministrativeRegion\Region;
use Biz\service\Store\StoreUserConsult;
use Biz\cache\store\StoreCallAndReserve;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\otherRedis;

class ReserveAction extends ActionPlugin
{
    const DEFAULT_ERROR_CODE = self::CODE_ERROR_VIEW_TOSTA;
    const USER_LEVEL = self::LEVEL_REGISTER;
    const VALIDATOR_TOAST_DEBUG = true;

    //参数校验-规则
    public const VALIDATOR_RULES = [
        'store_id' => 'require|integer',
        'phone' => 'require|number',
//        'area' => 'require',
//        'city_id' => 'require',
//        'area_code' => 'require',
//        'area_name' => 'require',
        'type' => 'require',
        'wiki_id' => 'integer',
    ];
    //参数校验-自定义消息
    public const VALIDATOR_MSG = [
        'store_id.require' => 'store_id缺失',
        'phone.require' => '电话号码缺失',
        'phone.number' => '手机号格式错误',
        'area_code.require' => '地址码缺失',
        'area_name.require' => '地址缺失',
    ];

    /**
     * @throws Exception
     */
    public function main()
    {
        $store_id = $this->params['store_id'];
        $phone = $this->params['phone'];
        $city_id = $this->params['city_id'];
        $act_from = $this->params['type'];
        $wiki_id = $this->params['wiki_id'] ?? 0;
        $area_code = $this->params['area_code'];


        if (!$area_code) {
            $codes = explode(",", $city_id);
            $code = array_pop($codes);
            $area_code = Region::getCodeByOldCode($code);
        }
        if (!$city_id) {
            $city_id = Region::getOldCodeByAreaCode($area_code);
        }

        $area_name = $area_code ? Region::getAreaDetailByCode($area_code) : '';
        $rs = StoreUserConsult::AddConsultInfo($this->uid, $store_id, $phone, $area_name, $city_id, $act_from, $wiki_id,
            $area_code, $area_name);
        if (!$rs) {
            throw new Exception("预约失败", self::CODE_ERROR_VIEW_TOSTA);
        }

        //缓存用户留资次数
        StoreCallAndReserve::setUserReserveStore($this->uid, $store_id);

        //迁移
//        $constKey = redisKeys::KEY_B_OTHER_USER_STORE_RESERVE_;
//        $redis = new otherRedis($constKey);
//        $key = $constKey.$this->uid;
//
//        $redis->sadd($key,$store_id);
//        $end_time =  strtotime(date('Y-m-d')) + 86400;
//        $redis->expireat($key,$end_time);


        ActionLog::log($this->uid, [
            'uid' => $this->uid,
            'store_id' => $store_id,
            'phone' => $phone,
            'area' => $area_name,
            'area_code' => $area_code,
            'act_from' => $act_from
        ], ActionLog::STORE_ACTIVITY_CONSULT);
        return $this->setSuccess(['msg' => 'success']);

    }


}